<?php
/**
 * TestLink Open Source Project - http://testlink.sourceforge.net/ 
 * This script is distributed under the GNU General Public License 2 or later. 
 *
 * @package 	TestLink
 * @copyright 	2007, TestLink community 
 * @version    	CVS: $Id: migrate_16_to_17_functions.php,v 1.11 2009/08/29 23:57:28 havlat Exp $
 *
 * @internal Revisions:
 * 		20080830 - havlatm - 0002699: Update of 1.7 to 1.8 fails because connect_2_db() is MySQL specific
 *      20071103 - franciscom - BUGID 771 - utf-8 issue - contributed by eagleas
 *
 *      20071008 - asielb - fixed bug 1110, keywords migration
 *      20070829 - jbarchibald - fixed bug 1010, results Migration
 */

/**
 * Tries to connect to a database, displaying ALWAYS an status message.
 */
// args   :
//         cfg=array('db_type' => 'mysql',
//                   'db_server' => '10.1.2.242',
//                   'db_admin_name' => 'root',
//                   'db_admin_pass' => 'password',
//                   'log_level' => );
// returns: 
//          if connection OK -> a database object
//          if connection KO -> null
//
// rev :
//      20080219 - franciscom - added log_level
//      20061203 - franciscom - removed warning due to constant redefinition
function connect_2_db($cfg)
{

	if( !defined('NO_DSN') )
	{
  		define('NO_DSN',FALSE);
	}

	if(strlen(trim($cfg['db_name']))== 0)
	{
		echo '<span class="notok">Failed!</span><p />Database Name is empty';
		$db=null;
	}
	else
	{  
		$db = new database($cfg['db_type']);
		@$conn_result = $db->connect(NO_DSN,$cfg['db_server'], 
				$cfg['db_admin_name'], $cfg['db_admin_pass'],$cfg['db_name']); 
  
		if( $conn_result['status'] == 0 ) 
		{
			echo '<span class="notok">Failed!</span><p />Please check the database login details and try again.';
			echo '<br>Database Error Message: ' . $db->error_msg() . "<br>";
			$db=null;
		} 
		else 
		{
			if (!isset($cfg['db_type']) || strtolower($cfg['db_type']) == 'mysql') 
			{
			    // 20071103 - BUGID 771 eagleas
    			$db->exec_query("SET CHARACTER SET utf8;");
	    		$db->exec_query("SET collation_connection = 'utf8_general_ci';");
			}
			//echo "<span class='ok'>OK!</span><p />";
			print_msg("<span class='ok'>OK!</span><p />");
		}
	}

	return ($db);
}

// determine if the version of the db being used is > 5.x
function determine_mysql_version($db_connection_obj)
{
	$query="SELECT VERSION() as ver";
	$source_version = $db_connection_obj->fetchFirstRow($query);
	// searching for MySQL version 5 or higher should have String like one of the following
	// 5.0.41-community-nt || 5.0.22-Debian_0ubuntu6.06.3-log
	return preg_match("/^5.\d+.\d+/", $source_version["ver"]);		
}



// print messages according to whether FULL_FEEDBACK is set
function print_msg($msg)
{
	$print_level = PRINT_LEVEL;
	if($print_level == 'NORMAL')
	{
		echo $msg;			
	}
	else
	{
		//echo $msg;		
	}
	// always flush the output buffer and send it
	flush();
	@ob_flush();
}

// To return a byte value for the memory available
// Used from: http://us.php.net/manual/en/function.ini-get.php
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

// This should increase memory to a sufficient amount for most cases if necessary
// or error out before we are in the middle of converting tcs
function check_memory($tc_count)
{ 
  $memory_available = return_bytes(ini_get("memory_limit"));
  // 67108864 = 64M
  if ($memory_available <= 67108864 && $tc_count > 5000)
  {
  	// should be >= 128M
  	$new_limit = "384M";
  	// attempt to set the memory_limit to $new_limit to avoid problems
  	if (false == ini_set("memory_limit", $new_limit))
  	{
	  	print_msg("</div><h1><center>You have $tc_count testcases and a memory limit of " .
	  			ini_get("memory_limit") . " <br />" .
	  			"Try increasing your memory_limit to " .
	  			"at least 128M in your php.ini</center></h1>");
	  	// this is pretty harsh but it has been shown to not work so its probably better than 
	  	//blowing up in the middle of the conversion process. Remove at your own risk!
	  	exit(1);
  	}
  	else
  	{
  		print_msg("Increased your memory_limit to $new_limit");
  	}
  }
}



?>
